package com.example.demo.config;

import java.io.IOException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * @author kaixuan.xu
 * @version 1.0.0
 * @time 2019/2/17 13:26
 * @description
 */
@SpringBootConfiguration
public class MyBatisConfig {

  @Autowired
  private DataSource dataSource;

  @Value("${mybatis.mapper-locations}")
  private String mapperLocation;

  @Value("${mybatis.type-aliases-package:}")
  private String typeAliasesPackage;

  @Bean
  public SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws Exception {

    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources(mapperLocation));
    sqlSessionFactoryBean.setDataSource(dataSource);
    sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
    return sqlSessionFactoryBean.getObject();
  }

}
